import Taro, { Component, Config, useState, useRouter, useEffect, useCallback } from '@tarojs/taro'
import { View, Text, Video, ScrollView, Image } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { AtIcon } from 'taro-ui'
import { formatCount, formatNumber, formatTimeStampToTime } from '../../utils/index'
import WhiteSpace from '../../components/WhiteSpace/WhiteSpace'
import Loading from '../../components/Loading/Loading'
import { mvDetail, artists, mvUrl, simiMv, comment, videoDetail, getvideoUrl, videoRelated } from '../../api/base'
import classnames from 'classnames'
import './index.scss'

type videoInfo = {
  coverUrl: string
  title: string
  shareCount: number
  playTime: number
  praisedCount: number
  commentCount: number
  subscribeCount: number
  creator: {
    nickname: string
    avatarUrl: string
  }
  videoGroup: Array<{ id: number; name: string }>
}

type relatedList = Array<{
  vid: string
  title: string
  durationms: number
  playTime: number
  coverUrl: string
  creator: Array<{
    userName: string
  }>
}>
type mvInfo = {
  cover: string
  name: string
  briefDesc: string
  desc: string
  shareCount: number
  playCount: number
  likeCount: number
  commentCount: number
  subCount: number
  artists: Array<{
    name: string
    id: number
  }>
  avatarUrl: string
  publishTime: string
}
type commentInfo = {
  commentList: Array<{
    content: string
    commentId: number
    time: number
    likedCount: number
    liked: boolean
    user: {
      avatarUrl: string
      nickname: string
      userId: number
    }
  }>
  more: boolean
}
type mvRelatedList = Array<{
  id: string
  name: string
  duration: number
  playCount: number
  cover: string
  artistName: string
}>
function VideoDetail(props) {
  const {} = props
  const [videoInfo, setVideoInfo] = useState<videoInfo>({
    coverUrl: '',
    title: '',
    shareCount: 0,
    playTime: 0,
    praisedCount: 0,
    commentCount: 0,
    subscribeCount: 0,
    creator: {
      nickname: '',
      avatarUrl: ''
    },
    videoGroup: []
  })
  const [videoUrl, setVideoUrl] = useState<string>('')
  const [relatedList, setRelatedList] = useState<relatedList>([])
  const [mvInfo, setMvInfo] = useState<mvInfo>({
    cover: '',
    name: '',
    briefDesc: '',
    desc: '',
    shareCount: 0,
    playCount: 0,
    likeCount: 0,
    commentCount: 0,
    subCount: 0,
    artists: [],
    publishTime: '',
    avatarUrl: ''
  })
  const [mvRelatedList, setMvRelatedList] = useState<mvRelatedList>([])
  const [showMoreInfo, setShowMoreInfo] = useState<boolean>(false)
  const [type, setType] = useState<any>('')
  const [commentInfo, setCommentInfo] = useState<commentInfo>({
    commentList: [],
    more: true
  })
  const params = useRouter().params
  useEffect(() => {
    let { id, type } = params
    setType(type)
    type == 'mv' ? getMvDetail(id) : getVideoDetail(id)
    getCommentInfo()
  }, [params])
  const getMvDetail = useCallback(async (id) => {
    const videoContext = Taro.createVideoContext('myVideo')
    videoContext.pause()
    let { data } = await mvDetail({ mvid: id })
    let { artist } = await artists({ id: data.artists[0].id })
    let {
      data: { url }
    } = await mvUrl({ id })
    let { mvs } = await simiMv({ mvid: id })
    let mvInfo = { ...data, avatarUrl: artist.picUrl }
    setMvInfo(mvInfo)
    setVideoUrl(url)
    setMvRelatedList(mvs)
  }, [])
  const getCommentInfo = useCallback(async () => {
    let { id, type } = params
    let { comments, more } = await comment(type, { id, limit: 20, offset: commentInfo.commentList.length })
    setCommentInfo({
      commentList: commentInfo.commentList.concat(comments),
      more
    })
  }, [commentInfo])
  const getVideoDetail = useCallback(async (id) => {
    const videoContext = Taro.createVideoContext('myVideo')
    videoContext.pause()
    let { data } = await videoDetail({ id })
    let {
      data: { urls }
    } = await getvideoUrl({ id })
    let { mvs } = await videoRelated({ id })
    setMvInfo(data)
    setVideoUrl(urls[0].url)
    setMvRelatedList(mvs)
  }, [])
  const formatDuration = useCallback((ms: number) => {
    // @ts-ignore
    let minutes: string = formatNumber(parseInt(ms / 60000))
    // @ts-ignore
    let seconds: string = formatNumber(parseInt((ms / 1000) % 60))
    return `${minutes}:${seconds}`
  }, [])
  const getDetailByType = useCallback(
    (id) => {
      const { type } = params
      type === 'mv' ? getMvDetail(id) : getVideoDetail(id)
    },
    [params]
  )
  return (
    <View className="video">
      <Video
        src={videoUrl}
        controls={true}
        autoplay={false}
        poster={type === 'video' ? videoInfo.coverUrl : mvInfo.cover}
        className="player"
        loop={false}
        muted={false}
        id="myVideo"
      />
      <ScrollView scrollY className="video-scroll" onScrollToLower={() => getCommentInfo()}>
        {!videoInfo.title && !mvInfo.name ? <Loading /> : ''}
        {type === 'video' ? (
          <View className="">
            <View className="row2 xl item"> {videoInfo.title}</View>
            <View className="video-desc mb20 flex wrap item">
              <Text className="col-hui l">{formatCount(videoInfo.playTime)}次观看</Text>
              {videoInfo.videoGroup.map((videoGroupItem) => (
                <Text className="video-tag" key={videoGroupItem.id}>
                  {videoGroupItem.name}
                </Text>
              ))}
            </View>
            <View className="flex middle around mb20 item">
              <View className="flex-item">
                <AtIcon prefixClass="fa" value="thumbs-o-up" size="24" color="#323232"></AtIcon>
                <View className="video-num">{videoInfo.praisedCount}</View>
              </View>
              <View className="flex-item">
                <AtIcon value="star" size="24" color="#323232"></AtIcon>
                <View className="video-num">{videoInfo.subscribeCount}</View>
              </View>
              <View className="flex-item">
                <AtIcon value="message" size="24" color="#323232"></AtIcon>
                <View className="video-num">{videoInfo.commentCount}</View>
              </View>
              <View className="flex-item">
                <AtIcon value="share" size="24" color="#323232"></AtIcon>
                <View className="video-num">{videoInfo.shareCount}</View>
              </View>
            </View>
            <View className="flex middle item">
              <Image src={videoInfo.creator.avatarUrl} className="video-avarar" />
              <Text>{videoInfo.creator.nickname}</Text>
            </View>
          </View>
        ) : (
          <View className="">
            <View className="flex between xl item">
              <View className="cell-main"> {mvInfo.name}</View>
              <AtIcon
                value={showMoreInfo ? 'chevron-up' : 'chevron-down'}
                size="20"
                color="#323232"
                onClick={() => setShowMoreInfo((showMoreInfo) => !showMoreInfo)}
              ></AtIcon>
            </View>
            <View className="video-desc item">
              <Text className="col-hui l">{formatCount(videoInfo.playTime)}次观看</Text>
            </View>
            {showMoreInfo ? (
              <View className="video-descinfo item">
                <View>发行： {mvInfo.publishTime}</View>
                <WhiteSpace size="xs" color="#ffffff" />
                <View>{mvInfo.briefDesc}</View>
                <WhiteSpace size="xs" color="#ffffff" />
                <View>{mvInfo.desc}</View>
              </View>
            ) : null}
            <View className="flex middle around item">
              <View className="flex-item">
                <AtIcon prefixClass="fa" value="thumbs-o-up" size="24" color="#323232"></AtIcon>
                <View className="video-num">{mvInfo.likeCount}</View>
              </View>
              <View className="flex-item">
                <AtIcon value="star" size="24" color="#323232"></AtIcon>
                <View className="video-num">{mvInfo.subCount}</View>
              </View>
              <View className="flex-item">
                <AtIcon value="message" size="24" color="#323232"></AtIcon>
                <View className="video-num">{mvInfo.commentCount}</View>
              </View>
              <View className="flex-item">
                <AtIcon value="share" size="24" color="#323232"></AtIcon>
                <View className="video-num">{mvInfo.shareCount}</View>
              </View>
            </View>
            <View className="flex middle item">
              <Image src={mvInfo.avatarUrl} className="video-avarar" />
              <Text>{mvInfo.artists[0].name}</Text>
            </View>
          </View>
        )}
        <WhiteSpace size="sm" color="#f8f8f8" />
        <View className="video-relation">
          <View className="xl item">相关推荐</View>
          {type === 'video' ? (
            <View>
              {!relatedList.length ? <Loading /> : ''}
              {relatedList.map((item) => (
                <View key={item.vid} onClick={() => getDetailByType(item.vid)} className="video-item flex">
                  <View className="video-imgbox">
                    <Image className="video-pic" src={item.coverUrl}></Image>
                    <View className="video-playtag">
                      <Text className="at-icon at-icon-play"></Text>
                      <Text>{formatCount(item.playTime)}</Text>
                    </View>
                  </View>
                  <View className="cell-main ml10">
                    <View className="row2 video-pushName l">{item.title}</View>
                    <View className="col-hui l">
                      {formatDuration(item.durationms)},by {item.creator[0].userName}
                    </View>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            <View>
              {!mvRelatedList.length ? <Loading /> : ''}
              {mvRelatedList.map((item) => (
                <View key={item.id} onClick={() => getDetailByType(item.id)} className="video-item flex">
                  <View className="video-imgbox">
                    <Image className="video-pic" src={item.cover}></Image>
                    <View className="video-playtag">
                      <Text className="at-icon at-icon-play"></Text>
                      <Text>{formatCount(item.playCount)}</Text>
                    </View>
                  </View>
                  <View className="cell-main ml10">
                    <View className="row2 video-pushName l">{item.name}</View>
                    <View className="col-hui l">
                      {formatDuration(item.duration)},by {item.artistName}
                    </View>
                  </View>
                </View>
              ))}
            </View>
          )}
        </View>
        <WhiteSpace size="sm" color="#f8f8f8" />
        <View className="video-relation">
          <View className="xl item">精彩评论</View>
          <View className="item">
            {commentInfo.commentList.map((item) => (
              <View className="flex ">
                <Image src={item.user.avatarUrl} className="comment-avatar" />
                <View className="cell-main">
                  <View className="flex middle">
                    <View className="cell-main">
                      <View className="xl mb10">{item.user.nickname}</View>
                      <View className="l col-hui ">{formatTimeStampToTime(item.time)}</View>
                    </View>
                    <View
                      className={classnames('video-like', {
                        like: item.liked
                      })}
                    >
                      {item.likedCount ? item.likedCount : ''}
                      <AtIcon prefixClass="fa" value="thumbs-o-up" size="12" color="#323232"></AtIcon>
                    </View>
                  </View>
                  <View className="video-comment">{item.content}</View>
                </View>
              </View>
            ))}
            {commentInfo.more ? <Loading /> : ''}
          </View>
        </View>
      </ScrollView>
    </View>
  )
}
VideoDetail.config = {
  navigationBarTitleText: '精彩视频'
}
export default connect(
  function mapStateToProps(state) {
    return state
  },
  function mapDispatchToProps(dispatch) {
    return { dispatch }
  }
)(VideoDetail)
